package com.chalk.controller;

import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.chalk.common.plugins.fastdfs.FastDFSClient;
import com.chalk.common.util.RestTemplateUtil;
import com.chalk.common.util.Result;
import com.chalk.common.util.ResultCode;
import com.chalk.config.base.BaseController;
import com.chalk.dto.MiniQrDto;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;


/**
 * 对接微信Controller
 * @author mxq
 * @date 2019年04月22日 下午2:06:26
 * 
 */

@RestController
@RequestMapping(value="/wx")
public class WxController extends BaseController {
	
	private static final Logger log = LoggerFactory.getLogger(WxController.class);

	@Value("${wx-mini.appId}")
	private String miniAppId;

	@Value("${wx-mini.appsecret}")
	private String miniAppsecret;

	@Value("${fdfs.server-path}")
	private String serverPath;

	@Autowired
	private RestTemplateUtil<String> restTemplateUtil;

	@Autowired
	private FastDFSClient fastDFSClient;









	/**
	 * 获取小程序码（base64）
	 * @param miniQrDto
	 * @param response
	 * @return
	 */
	@PostMapping("/getminiqrQr")
	public Result getminiqrQr(@Validated MiniQrDto miniQrDto, HttpServletResponse response){
		RestTemplate rest = new RestTemplate();

			String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+getMiniToken();
			Map<String,Object> param = new HashMap<>();
			param.put("scene", miniQrDto.getScene());
			param.put("page", miniQrDto.getPage());
			param.put("width", 430);
			param.put("auto_color", false);
			Map<String,Object> lineColor = new HashMap<>();
			lineColor.put("r", 0);
			lineColor.put("g", 0);
			lineColor.put("b", 0);
			param.put("line_color", lineColor);
			log.info("调用生成微信URL接口传参:" + param);
			MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
			headers.set("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
			HttpEntity requestEntity = new HttpEntity(param, headers);
			ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
			try {
				JSONObject jsonObject = JSONUtil.parseObj(new String(entity.getBody()));
				// 请求错误时返回Json对象
				if (StringUtils.isNotBlank(jsonObject.get("errcode").toString())){
					return Result.fail(jsonObject);
				}
			}catch (JSONException e){
				logger.info("获取小程序码成功");
			}
		// 给前端返回
		Map<String, Object> result = new HashMap<>(2);
		InputStream inputStream = null;
		String imageUrl = null;
		try {
			inputStream = new ByteArrayInputStream(entity.getBody());
			imageUrl = fastDFSClient.uploadStream(inputStream, entity.getBody().length, "112.png");
			result.put("imageUrl", serverPath+imageUrl);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 成功返回图片二进制  转为base64给前端
		String s = Base64.encodeBase64String(entity.getBody());
		result.put("baseData","data:image/png;base64," + s);
		return Result.success(result);

	}

	/**
	 * 获取小程序码(返回二进制流)
	 * @param miniQrDto
	 * @param response
	 * @return
	 */
	@PostMapping("/getminiStreamQr")
	public void getminiStreamQr(@Validated MiniQrDto miniQrDto, HttpServletResponse response){
		RestTemplate rest = new RestTemplate();

		String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+getMiniToken();
		Map<String,Object> param = new HashMap<>();
		param.put("scene", miniQrDto.getScene());
		param.put("page", miniQrDto.getPage());
		param.put("width", 430);
		param.put("auto_color", false);
		Map<String,Object> lineColor = new HashMap<>();
		lineColor.put("r", 0);
		lineColor.put("g", 0);
		lineColor.put("b", 0);
		param.put("line_color", lineColor);
		log.info("调用生成微信URL接口传参:" + param);
		MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
		headers.set("Content-Type", MediaType.APPLICATION_JSON_UTF8_VALUE);
		HttpEntity requestEntity = new HttpEntity(param, headers);
		ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
		try {
			JSONObject jsonObject = JSONUtil.parseObj(new String(entity.getBody()));
			// 请求错误时返回Json对象
			if (StringUtils.isNotBlank(jsonObject.get("errcode").toString())){
				response.setStatus(6000);
			}
		}catch (JSONException e){
			logger.info("获取小程序码成功");
		}
		// 转为base64
//		String s = Base64.encodeBase64String(entity.getBody());
//		logger.info("Base64:" + "data:image/png;base64," + s);
		response.setDateHeader("Expires", 0L);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/png");
		ServletOutputStream outputStream = null;
		try {
			outputStream = response.getOutputStream();
			outputStream.write(entity.getBody(),0, entity.getBody().length);
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				outputStream.flush();
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 微信小程序获取accessToken
	 * @return
	 */
	private String getMiniToken(){
		String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+miniAppId+"&secret="+miniAppsecret;
		String resultToken = restTemplateUtil.doGet(tokenUrl).getBody();
		JSONObject jsonObject = JSONUtil.parseObj(resultToken);
		return (String) jsonObject.get("access_token");
	}


	/**
	 * 图片转base64
	 *
	 * @param imageUrl
	 * @return
	 */
	@ApiOperation(value = "图片转base64", notes = "图片转base64", response = Result.class)
	@PostMapping("/imageConvertBase64")
	public Result imageConvertBase64(@ApiParam(name = "imageUrl", value = "图片地址", required = true) @RequestBody String imageUrl) throws IOException {
		URL url = new URL(imageUrl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		//设置请求方式为"GET"
		conn.setRequestMethod("GET");
		//超时响应时间为5秒
		conn.setConnectTimeout(5 * 1000);
		InputStream stream = null;
		ByteArrayOutputStream outputStream = null;
		try {
			stream = conn.getInputStream();
			outputStream = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int n = 0;
			while ((n = stream.read(b)) != -1) {
				outputStream.write(b, 0, n);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			outputStream.flush();
			outputStream.close();
			stream.close();
		}
		BASE64Encoder encoder = new BASE64Encoder();
		String s = "data:image/png;base64," + encoder.encode(outputStream.toByteArray());
		System.out.println("--->"+s);
		return Result.success(ResultCode.SUCCESS, s);
	}

}
